import { createI18n, useI18n } from 'vue-i18n'
import { computed } from 'vue'
import lang from './lang/index'
import type { Ref } from 'vue'

export const i18n = createI18n({
  locale: 'zh',
  fallbackLocale: 'zh',
  legacy: false,
  globalInjection: true,
  messages: lang
})

/** 切换语言
 */
type UseChangeI18n = {
  locale: Ref<string>
  currentLang: Ref<string>
  changeLang: (lang?: string) => void
}
export const useChangeI18nHook = (): UseChangeI18n => {
  const { locale, t } = useI18n()

  const currentLang = computed(() => {
    const { locale } = useI18n()
    return t(`lang.${locale.value}`).replace(/"/g, '')
  })

  const changeLang = (lang?: string): void => {
    locale.value = lang ? lang : locale.value === 'zh' ? 'en' : 'zh'
  }

  return {
    locale,
    currentLang,
    changeLang
  }
}
